﻿using System;
using System.Data.Common;
using System.Collections.Generic;
using Sinacor.Infra.Service.Data;
using Sinacor.Infra.Service.Security.Authorization;

namespace Sinacor.Servico.Bovespa.Contabil.ResourceAccess
{
    /// <summary>
    /// ResourceAccess Class - Municipio
    /// </summary>
    public class Municipio : BaseResourceAccess
    {
        #region Construtor

        /// <summary>
        /// Construtor
        /// </summary>
        public Municipio() : base(AuthorizationContext.Current.CompanyId) { }

        #endregion

        #region Métodos Públicos

        #region ConsultarMunicipios

        /// <summary>
        /// Serviço irá Consultar uma lista de Municipios
        /// </summary>
        /// <returns>Lista de objetos do tipo BusinessEntity.Municipio</returns>
        public List<BusinessEntity.Municipio> ConsultarMunicipios()
        {
            List<BusinessEntity.Municipio> response = new List<BusinessEntity.Municipio>();

            String sql = @"SELECT CD_MUNICIPIO Codigo,
                                  NM_MUNICIPIO Descricao
                             FROM TSCMUNICIPIO 
                         ORDER BY NM_MUNICIPIO";

            using (DbCommand dbCommand = this.DataBase.GetSqlStringCommand(sql))
            {
                response = this.FindAll<BusinessEntity.Municipio>(dbCommand,
                    reader =>
                    {
                        BusinessEntity.Municipio entity = new BusinessEntity.Municipio();

                        entity.Codigo = reader.GetValue<Int32>("Codigo");
                        entity.Descricao = reader.GetValue<String>("Descricao");

                        return entity;
                    });

                return response;
            }
        }

        #endregion

        #region ObterMenorCodigoMunicipio

        /// <summary>
        /// Obtem o menor código de município
        /// </summary>
        /// <returns>Int32</returns>
        public Int32 ObterMenorCodigoMunicipio()
        {
            String sql = @"SELECT MIN(TSCMUNICIPIO.CD_MUNICIPIO) MenorCodigoMunicipio
                             FROM TSCMUNICIPIO";

            using (DbCommand dbCommand = this.DataBase.GetSqlStringCommand(sql))
            {
                return Int32.Parse(this.DataBase.ExecuteScalar(dbCommand).ToString());
            }
        }

        #endregion

        #endregion
    }
}
